package cn.kgc.shiro;

import cn.kgc.shiro.realm.CustomerRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;
import java.util.List;

/**
 * shiro授权操作   授权操作需要再通过认证之后
 */
public class App {
    public static void main(String[] args) {

        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        CustomerRealm realm = new CustomerRealm();

        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        md5.setHashIterations(10);
        realm.setCredentialsMatcher(md5);

        securityManager.setRealm(realm);
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        String username = "root";
        String password = "123456";

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        subject.login(usernamePasswordToken);


        /*
        * 认证通过   如果用户访问的是受限资源  则会调用realm中的授权方法
        *  shiro中实现资源管理的方式主要有两种:
        *  1. 编程式权限控制
        *    user   select  /user/update  /user/delete   /user/insert
        *
        *    sys:user:select  查询权限字符串
        *    sys:user:delete  删除权限字符串
        *    sys:user:update  更新权限字符串
        *    sys:user:insert  添加权限字符串

        *  2.注解式权限控制   web
        *
        * */
        System.out.println("--------------shiro中基于角色的权限判定----------------------");
        boolean b = subject.hasRole("admin");
        System.out.println("b = " + b);

        List<String> list = Arrays.asList("admin", "super");
        boolean[] booleans = subject.hasRoles(list);
        System.out.println("booleans = " + Arrays.toString(booleans));

        boolean b1 = subject.hasAllRoles(list);
        System.out.println("b1 = " + b1);

        System.out.println("--------------shiro中基于权限字符串的权限判定----------------------");
        boolean permitted = subject.isPermitted("sys:user:select");
        System.out.println("permitted = " + permitted);
        boolean permittedAll = subject.isPermittedAll("sys:user:select", "sys:user:delete");
        System.out.println("permittedAll = " + permittedAll);


        // RBAC 设计思想   基于角色的权限控制    基于资源的权限控制    5张表
        // user  user_role    role   role_permission   permission

    }
}
